package hr.web.jsf.validators;

import hr.web.jsf.JSFUtils;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.international.Messages;

/*<h:outputLabel value="New password :" for="newPassword" />
 <h:inputSecret id="newPassword" value="#{userCrud.newPassword}">
 <f:validator validatorId="validator.compareFields" />
 <f:attribute name="compareTo" value="confirmPassword" />
 </h:inputSecret>
 <h:outputLabel value="Confirm password :" for="confirmPassword" />
 <h:inputSecret id="confirmPassword" value="#{userCrud.confirmPassword}"  />*/

@BypassInterceptors
@Name(value = "compareFieldsValidator")
@org.jboss.seam.annotations.faces.Validator
public class CompareFieldsValidator implements Validator {
	public void validate(FacesContext context, UIComponent cmp, Object value)
			throws ValidatorException {
		String compareTo = (String) cmp.getAttributes().get("compareTo");
		String messageKey = (String) cmp.getAttributes().get("message");
		UIInput input = (UIInput) JSFUtils.findComponent(context.getViewRoot(),
				compareTo);
		String otherValue = (String) input.getValue();
		boolean error = false;
		if (value != null) {
			if (!value.equals(otherValue)) {
				error = true;
			}
		} else {
			if (otherValue != null) {
				error = true;
			}
		}
		if (error) {
			String msg = Messages.instance().get(messageKey);
			throw new ValidatorException(new FacesMessage(msg));
		}
	}
}
